/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import Utility.PrimaryKeyReturnValue;
import Utility.VarcharUpdater;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import vo.rb_raw_mat_stock;
import vo.rb_raw_materials;

/**
 *
 * @author Shuhail
 */
public class rb_raw_materials_persist {
    
    Session sess=null;
    Transaction tx=null;
    public static rb_raw_materials_persist getInstance() {
        
        return new rb_raw_materials_persist();
    }
    
    public rb_raw_materials_persist() {
        
        SessionFactory sf=new Configuration().configure().buildSessionFactory();
        sess=sf.openSession();
        tx=sess.beginTransaction();
    }
    
    public List<rb_raw_materials> fetch() {
        tx.begin();
        Query query=sess.getNamedQuery("getAllRawMaterials");
        List<rb_raw_materials> manufacture_list=query.list();
        return manufacture_list;
        
    }
    
    public boolean insert(rb_raw_materials mat) {
        tx.begin();
        List<rb_raw_materials> list=this.fetch();
        List<String> pk_list=new ArrayList<String>();
        Iterator it=list.iterator();
        while(it.hasNext()){
            rb_raw_materials material=(rb_raw_materials)it.next();
            pk_list.add(material.getRaw_mat_id());
        }
        String last_pk=VarcharUpdater.getInstance().getTheLastPK(pk_list);
        mat.setRaw_mat_id(VarcharUpdater.getInstance().getValue(last_pk));
        System.out.println("-----Generated key ----:"+mat.getRaw_mat_id());
        rb_raw_materials mat_new=new rb_raw_materials();
        mat_new.setRaw_mat_id(mat.getRaw_mat_id());
        mat_new.setRaw_mat_name(mat.getRaw_mat_name());
        mat_new.setRaw_mat_type(mat.getRaw_mat_type());
        try{
        sess.save(mat_new);
        tx.commit();
        
        return true;
    }catch(Exception e) {
        return false;
    }
    }
}
